<template>
  <div class="left_side">
    <!-- @scroll="checkScroll" -->
    <div class="item_li" ref="chatContentBoxs">
      <div
        class="load_more"
        v-if="Number(total) / 10 > currentPage && Number(total) > 10"
        @click="getloadMoreData"
      >
        加载更多数据
      </div>
      <div class="on_more" v-if="Number(total) / 10 < currentPage && Number(total) > 10"
        >没有更多了</div
      >
      <div v-for="(item, index) in activeList" :key="index" class="li_c">
        <div class="oneself_c" v-if="item.empId == UserStore.userInfo.id">
          <div
            class="item_c"
            v-if="index > 0 && item.createTime == activeList[index - 1].createTime ? false : true"
          >
            {{ item.createTime }}
          </div>
          <div class="top_note">
            <div class="user">
              <p class="item_name">{{ item.emp }}</p>
              <el-image
                class="avatar"
                fit="cover"
                :src="item.avatar ? item.avatar : image"
              ></el-image>
            </div>

            <div class="content_c">
              <div class="text_c" v-if="item.content">
                <span v-html="item.content.replace(/\n/g, '<br/>')"></span>
              </div>
              <div v-if="item.annexs.length > 0" class="img_container">
                <!--图片-->
                <el-image
                  v-for="(img, imgIndex) in item.annexs"
                  :key="imgIndex"
                  class="img_c"
                  :lazy="true"
                  fit="contain"
                  style="
                    width: 100px;
                    height: 100px;
                    border: 1px solid #ebeef5;
                    border-radius: 4px;
                    box-sizing: border-box;
                    padding: 12px;
                  "
                  :initial-index="imgIndex"
                  :preview-src-list="item.annexs"
                  :src="img"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <div
            class="item_c"
            v-if="index > 0 && item.createTime == activeList[index - 1].createTime ? false : true"
          >
            {{ item.createTime }}
          </div>
          <div class="top_note">
            <div class="user">
              <el-image
                :size="24"
                class="avatar"
                fit="cover"
                :src="item.avatar ? item.avatar : image"
              ></el-image>
              <p class="item_name">{{ item.emp }}</p>
            </div>

            <div class="content_c">
              <div class="text_c" v-if="item.content">
                <span v-html="item.content.replace(/\n/g, '<br/>')"></span>
              </div>
              <!--图片-->
              <div class="img_container">
                <el-image
                  v-for="(img, imgIndex) in item.annexs"
                  :key="imgIndex"
                  class="img_c"
                  fit="contain"
                  style="
                    width: 100px;
                    height: 100px;
                    border: 1px solid #ebeef5;
                    border-radius: 4px;
                    box-sizing: border-box;
                    padding: 12px;
                  "
                  :lazy="true"
                  :preview-src-list="item.annexs"
                  :src="img"
                  :initial-index="imgIndex"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-if="activeList.length == 0" description="暂无留言" />
    </div>
    <!-- <template v-if="!$route.query.isArchive">
            <footer class="f_content">
                <div ref="contenteditableInputs" @focus="contentBlur" placeholder="发送留言..."
                    class="g-chat-container-footer-input" contenteditable="true">
                </div>
                <div class="upload_send">
                    <span class="btn_send" @click="sendInfoAction">发送</span>
                </div>
            </footer>
            <el-checkbox-group v-model="data.visitTypes" size="small" class="visit_type">
                <el-checkbox :label="0"><span class="visit_type_text">公开</span></el-checkbox>
                <el-checkbox :label="1"><span class="visit_type_text">服务商可见</span></el-checkbox>
                <el-checkbox :label="2"><span class="visit_type_text">工程师可见</span></el-checkbox>
                <el-checkbox :label="3"><span class="visit_type_text">客户可见</span></el-checkbox>
            </el-checkbox-group>
        </template> -->
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick, toRefs, reactive, watch } from 'vue'
  import type { UploadProps, UploadFile } from 'element-plus'
  import { useRoute } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getWorkLeaveMessageList, saveRemark } from '../../../../../api/order'
  import { orderAnnexUpload } from '../../../../../api/upload'
  import { useUserStore } from '../../../../../store/modules/user'
  import image from '@/assets/image/avatar.png'
  const props = defineProps({
    workId: [String, Array],
    workNo: String,
  })

  const chatContentBoxs = ref<HTMLElement | null>(null)
  const { workId, workNo } = toRefs(props)
  const activeList = ref([]) // 操作日志数据
  const total = ref(0)
  let pageSize = ref(10)
  let currentPage = ref(1)
  const UserStore = useUserStore()
  const route = useRoute()
  let data: any = reactive({
    annexs: [],
    remark: '',
    visitTypes: [0],
    workIds: [workId.value],
  })

  const imageUrls = ref([])
  // 获取图片
  // const handleChange: UploadProps["onChange"] = (uploadFile: UploadFile) => {
  //     let img = URL.createObjectURL(uploadFile.raw!)
  //     imageUrls.value.push(uploadFile.raw)
  //     const value = contenteditableInputs.value
  //     let image = new Image()
  //     image.src = img
  //     image.title = uploadFile.uid.toString()
  //     image.width = 40
  //     image.onload = function () {
  //         value.appendChild(image)
  //         keepLastIndex && keepLastIndex(value)
  //     }
  // }
  const range = ref<HTMLElement | null>(null)
  const selection = ref<any>(null)
  const contenteditableInputs = ref<HTMLElement | null>(null)
  const contentBlur = () => {
    /**
     * 每次焦点移出都要保存一次当前 range ，后面好放回来
     * 由于输入框以外的点击都会使输入框失去焦点，不知道会有什么操作，故勤保存
     */
    // range.value = selection.value.getRangeAt(0)
    scrollHeight()
  }
  // const focusContentEditable = () => {
  //     const editor = contenteditableInputs.value
  //     editor?.focus()
  //     // 获取选中的元素
  //     selection.value = document.getSelection()
  //     range.value = selection.value.getRangeAt(0)
  // }
  // const keepLastIndex = (obj) => {
  //     if (window.getSelection) {
  //         obj.focus() // 解决ff不获取焦点无法定位问题
  //         let range = window.getSelection() // 创建range
  //         range.selectAllChildren(obj) // range 选择obj下所有子内容
  //         range.collapseToEnd() // 光标移至最后
  //     }
  // }
  // 滚动到底部
  const scrollHeight = () => {
    nextTick(() => {
      setTimeout(() => {
        if (chatContentBoxs.value) {
          chatContentBoxs.value.scrollTop = chatContentBoxs.value.scrollHeight
        }
      }, 100)
    })
  }
  // 发送
  const sendInfoAction = async () => {
    let value = contenteditableInputs.value.innerHTML.trim() // 获取去除首尾空格的内容
    if (!value) {
      return ElMessage.error('请填写发送内容')
    }
    let img = []
    let imgIds = []
    let txt = /<div.*?>(.*?)<\/div>/gi
    let reg1 = /<img.*?title="(.*?)".*?>/gi
    let flag = value.match(reg1)
    if (value.match(txt)) {
      value = value.replace(txt, (item, $item) => {
        //找到图片做标书
        if ($item == '<br>') {
          return `\n`
        } else {
          return `\n${$item}`
        }
      })
    }
    // 过滤图片进行分割
    if (flag) {
      let content2 = value.replace(reg1, (item, $1) => {
        //找到图片做标书
        imgIds.push($1)
        return ``
      })
      imageUrls.value.filter((o) => {
        imgIds.filter((i) => {
          if (o.uid) {
            if (o.uid == i) {
              img.push(o)
            }
          } else {
            if (new Date(o.lastModifiedDate).getTime() == i) {
              img.push(o)
            }
          }
        })
      })
      data.remark = content2
    } else {
      data.remark = value
    }
    if (img.length > 0) {
      await orderAnnexUpload(img).then((res) => {
        if (res.data.code == 20000) {
          data.annexs = res.data.data.rows
          saveWorkLeave()
        }
      })
    } else {
      saveWorkLeave()
    }
  }
  // 保存留言
  function saveWorkLeave() {
    saveRemark(data).then(async (res) => {
      if (res.data.code == 20000) {
        await getList()
        scrollHeight() //滚动到底部
        contenteditableInputs.value.innerHTML = ''
        imageUrls.value = []
        data.remark = ''
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
        })
      }
    })
  }
  // 获取更多
  function getloadMoreData() {
    currentPage.value += 1
    if (Number(total.value) / 10 > currentPage.value) {
      let data = {
        limit: pageSize.value,
        page: currentPage.value,
      }
      getWorkLeaveMessageList(data, workId.value).then((res) => {
        if (res.data.success) {
          activeList.value = [...res.data.data.rows, ...activeList.value]
          total.value = Number(res.data.data.total)
          nextTick(() => {
            setTimeout(() => {
              chatContentBoxs.value.scrollTop = 600
            }, 0)
          })
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 4000,
          })
        }
      })
    }
  }
  // 获取留言列表
  async function getList() {
    let data = {
      limit: 10,
      page: 1,
    }
    await getWorkLeaveMessageList(data, workId.value).then((res) => {
      if (res.data.success) {
        activeList.value = res.data.data.rows
        total.value = Number(res.data.data.total)
        nextTick(() => {
          scrollHeight()
        })
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
        })
      }
    })
  }

  // 复制粘贴
  async function handlePaste(event) {
    const items = event.clipboardData?.items
    const clipboardData = event.clipboardData
    const pastedText = clipboardData.getData('text/plain')
    //   粘贴的文本
    event.preventDefault() // 阻止默认粘贴行为
    contenteditableInputs.value.innerHTML += pastedText
  }

  /**
   * @func 聊天框聚焦
   * @param e
   */
  onMounted(async () => {
    await getList()
    // if (!route.query.isArchive) {
    //     await nextTick()
    //     //     focusContentEditable()
    //     contenteditableInputs.value.addEventListener('paste', handlePaste);// 监听粘贴事件
    // }
  })
  // 向父组件传值
  defineExpose({ getList })
</script>
<style lang="scss" scoped>
  @import './../index.scss';

  .f_content {
    width: 100%;
    box-sizing: border-box;
    background-color: #fff;
    margin: 12px 0 0;

    .upload_send {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 8px 0;

      .btn_send {
        color: #007cff;
        font-size: 12px;
        cursor: pointer;
        margin-left: 8px;

        &:hover {
          color: #007cffab;
        }
      }

      .btn_uploading {
        cursor: pointer;
        font-size: 16px;
      }
    }

    :deep(.el-textarea .el-input__count) {
      right: 40px;
    }

    [contenteditable]:focus {
      outline: none;
    }

    [contenteditable]:empty:before {
      content: attr(placeholder);
      color: #cccccc;
      font-size: 12px;
    }

    .g-chat-container-footer-input {
      word-break: break-all;
      padding: 8px;
      white-space: pre-wrap;
      overflow: auto;
      height: 120px;
      flex: 1;
      width: 100%;
      box-sizing: border-box;
      overflow: auto;
      background-color: #f2f3f5;

      ::v-deep(.at-logo) {
        padding-right: 5px;
        vertical-align: text-bottom;
      }
    }
  }
</style>
